import { getQuestionApi } from "@/apis/question";
import { useComponentStore, useStore,useTemporalStore} from "@/store";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useParams } from "react-router-dom";




const useLoadQuestionData = () => {
  const {id= ''} = useParams()

  const store = useStore()
  const componentStore = useComponentStore()


  const {data,loading,error,run} = useRequest(async(id:string)=>{
    if(!id) throw new Error('id is required')
    const data = await getQuestionApi(id)
   
    return data 
  },{
    manual:true
  })

  useEffect(()=>{
    if(!data) return

    const {componentList = [],js,css,title,desc,isPublished} = data as any
    store.setPageInfo({title,desc,js,css,isPublished})
    componentStore.setComponentList(componentList)

    store.setSelectedId(componentList[0].fe_id)

    // 初始化数据时，清除形成临时数据
    setTimeout(() => {
      useTemporalStore.getState().clear();
    }, 0);

    
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[data])

  useEffect(()=>{
    run(id)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[id])


  return {data,loading,error}
}



export default useLoadQuestionData;